<template>
  <div class="sign" @touchmove="stopPageMove">
    <div>
      <div class="btn-content">
        <button @click="clear"><span>清</span><span>除</span></button>
        <button class="submit" @click="submit"><span>确</span><span>定</span></button>
      </div>
      <div ref="canvasContent" class="canvas-content">
        <canvas ref="canvas" id="canvas" canvas-id="canvas" v-if="canvasSize" :width="canvasSize.width" :height="canvasSize.height" :style="{ width: canvasSize.width + 'px', height: canvasSize.height + 'px' }" @touchstart="drawStart" @touchend="drawEnd" @touchmove="move" />
      </div>
    </div>
    <img ref="img" v-if="imgUrl" :src="imgUrl" style="position: absolute; opacity: 0; z-index: -1" @load="imgLoad" alt="">
  </div>
</template>

<script>
  export default {
    name: 'sign',
    data() {
      return {
        canvasSize: null,
        ctx: null,
        isDraw: false,
        startPointObj: {
          x: 0,
          y: 0,
        },
        imgUrl: '',
      };
    },
    mounted() {
      this.setCanvasSize();
      this.createCanvas();
    },
    created() {
      document.body.addEventListener('touchmove', this.stopPageMove, { passive: false });
    },
    beforeDestroy() {
      document.body.removeEventListener('touchmove', this.stopPageMove);
    },
    methods: {
      setCanvasSize() {
        const el = this.$refs.canvasContent;
        this.canvasSize = {
          width: el.clientWidth,
          height: el.clientHeight,
        };
      },
      createCanvas() {
        this.$nextTick(() => {
          this.ctx = uni.createCanvasContext('canvas', this);
        });
      },
      drawStart(e) {
        if (!this.ctx) {
          return;
        }
        // console.log(e, this.ctx);
        this.ctx.lineWidth = 4;
        this.ctx.lineCap = 'round';
        // this.ctx.lineJoin = 'round';
        this.ctx.strokeStyle = '#000000';
        this.startPointObj = e.touches[ 0 ];
        this.isDraw = true;
      },
      drawEnd(e) {
        if (!this.ctx) {
          return;
        }
        this.isDraw = false;
        // console.log(e);
      },
      move(e) {
        e.preventDefault();
        const { startPointObj, ctx, isDraw } = this;
        if (!(ctx && isDraw)) {
          return;
        }
        const point = e.touches[ 0 ];
        ctx.beginPath();
        ctx.moveTo(startPointObj.x, startPointObj.y);
        ctx.lineTo(point.x, point.y);
        ctx.stroke();
        ctx.closePath();
        ctx.draw(true);
        this.startPointObj = point;
      },
      clear() {
        const { canvasSize, ctx } = this;
        ctx.clearRect(0, 0, canvasSize.width, canvasSize.height);
        ctx.draw(true);
      },
      submit() {
        const that = this;
        uni.canvasToTempFilePath({
          canvasId: 'canvas',
          success(res) {
            // console.log(res);
            // const { blob, data } = that.baseToFile(res.tempFilePath);
            // const img = new Image();
            // img.onload = function () {
            //   const canvas = document.createElement('canvas');
            //   canvas.width = img.height;
            //   canvas.height = img.width;
            //   const ctx = canvas.getContext('2d');
            //   ctx.translate(0, canvas.height);
            //   ctx.rotate(-90 * Math.PI / 180);
            //   ctx.drawImage(img, 0, 0, canvas.height, canvas.width);
            //   // console.log(img);
            //   console.log(canvas.toDataURL());
            // };
            // img.src = that.getObjectURL(blob);
            that.imgUrl = res.tempFilePath;
            // img.setAttribute('crossOrigin', 'anonymous');
            // img.setAttribute('style', 'position:absolute;opacity:0');
            // document.body.appendChild(img);
          },
        });
      },
      baseToFile(data) {
        const arr = data.split(',');
        const mime = arr[ 0 ].match(/:(.*?);/)[ 1 ];
        const suffix = mime.split('/')[ 1 ];
        const bstr = atob(arr[ 1 ]);
        let n = bstr.length;
        const u8arr = new Uint8Array(n);
        const fileName = Math.random();
        while (n--) {
          u8arr[ n ] = bstr.charCodeAt(n);
        }
        const file = new File([ u8arr ], `${fileName}.${suffix}`, { type: mime });
        const blob = new Blob([ u8arr ], { type: mime });
        // console.log(file, blob);
        return { data, file, blob };
      },
      getObjectURL(blob) {
        if (window.createObjectURL) {
          return window.createObjectURL(blob);
        }
        if (window.URL) {
          return window.URL.createObjectURL(blob);
        }
        if (window.webkitURL) {
          return window.webkitURL.createObjectURL(blob);
        }
      },
      imgLoad() {
        const { imgUrl } = this.imgUrl;
        const img = this.$refs.img[ 0 ] || this.$refs.img;
        const canvas = document.createElement('canvas');
        canvas.width = img.clientHeight;
        canvas.height = img.clientWidth;
        const ctx = canvas.getContext('2d');
        ctx.translate(0, canvas.height);
        ctx.rotate(-90 * Math.PI / 180);
        ctx.drawImage(img, 0, 0, canvas.height, canvas.width);
        // console.log(img);
        console.log(canvas.toDataURL());
        this.imgUrl = '';
      },
      stopPageMove(e) {
        e.preventDefault();
        e.stopPropagation();
      },
      // aaa() {
      //   uni.switchTab({
      //     url: `/pages/index/index`,
      //   });
      // },
    },
  };
</script>

<style lang="scss" scoped>
  .sign {
    &, * {
      box-sizing: border-box;
    }
    height: 100vh;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    background-color: white;
    > div {
      padding: 15px;
      display: flex;
      height: 100%;
      .btn-content {
        margin-right: 15px;
        display: flex;
        flex-direction: column;
        justify-content: end;
        button {
          font-size: 12px;
          background-color: white;
          line-height: 1;
          padding: 10px;
          span {
            transform: rotateZ(90deg);
            display: block;
            padding: 5px 0;
          }
          & + button {
            margin-top: 15px;
          }
          &.submit {
            background-color: #409EFF;
            border-color: #409EFF;
            color: white;
          }
        }
      }
      .canvas-content {
        flex: 1;
        border: 1px solid #f1f1f1;
      }
    }
  }
</style>
